<!--
 * @description: 地图显示
 * @fileName: index.vue
 * @author: ssr
 * @date: 2022-08-12 09:38:14
 * @version: V1.0.0
!-->
<template>
  <div id="cesium-container-tuiyan" class="cesium-container"></div>
</template>
<script>
import * as Cesium from "cesium";
import { defineComponent, onBeforeUnmount, onActivated, onMounted, nextTick, ref } from "vue";
import { CustomViewer } from "@@/utils/CustomCesium/CustomCesium";
import { cesiumStateTuiyan, simulationStateTuiyan } from "@@/store-tuiyan/modules";

export default defineComponent({
  props: {
    customViewerTuiyan: {
      type: Object,
      default: () => null,
    },
  },
  emits: ["update:customViewerTuiyan", "viewer-ready"],
  setup(props, { emit }) {
    const store = cesiumStateTuiyan();
    const simulStore = simulationStateTuiyan()
    const isInitialized = ref(false);
    const viewerInstance = ref(null);
    const isInitializing = ref(false);
    const initRetryCount = ref(0);
    const MAX_RETRY_COUNT = 3;
    const INIT_TIMEOUT = 5000;

    // 销毁地图实例
    const destroyViewer = () => {
      if (viewerInstance.value) {
        try {
          const viewer = viewerInstance.value.viewer;
          if (viewer && !viewer.isDestroyed()) {
            viewer.entities.removeAll();
            viewer.dataSources.removeAll(true);
            viewer.destroy();
          }
          viewerInstance.value = null;
          store.setCustomViewerTuiyan(null);
        } catch (e) {
          console.error('销毁地图实例失败:', e);
        }
      }
      isInitialized.value = false;
      initRetryCount.value = 0;
    };

    // 检查 viewer 是否有效
    const isViewerValid = (viewer) => {
      if (!viewer) return false;
      if (!viewer.viewer) return false;
      if (viewer.viewer.isDestroyed()) return false;
      if (!viewer.viewer.scene) return false;
      if (!viewer.viewer.scene.globe) return false;
      return true;
    };

    // 等待 viewer 就绪
    const waitForViewerReady = async (viewer) => {
      return new Promise((resolve, reject) => {
        let attempts = 0;
        const maxAttempts = 50;
        const interval = 100;

        const checkViewer = () => {
          attempts++;
          if (isViewerValid(viewer)) {
            resolve(true);
          } else if (attempts >= maxAttempts) {
            reject(new Error('等待 viewer 就绪超时'));
          } else {
            setTimeout(checkViewer, interval);
          }
        };

        checkViewer();
      });
    };

    // 初始化地图
    const initMap = async () => {
      if (isInitializing.value) {
        return;
      }

      try {
        isInitializing.value = true;

        // 检查容器
        const container = document.getElementById('cesium-container-tuiyan');
        if (!container) {
          throw new Error('Cesium container not found');
        }

        // 如果存在旧的实例，先销毁
        if (viewerInstance.value) {
          destroyViewer();
        }

        // 设置初始化视框
        const extent = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = extent;

        // 创建新的 viewer 实例
        const customViewerTuiyan = new CustomViewer("cesium-container-tuiyan");

        // 等待 viewer 就绪
        try {
          await waitForViewerReady(customViewerTuiyan);
        } catch (error) {
          throw new Error('Viewer 初始化超时');
        }

        viewerInstance.value = customViewerTuiyan;

        // 更新 store
        store.setCustomViewerTuiyan(customViewerTuiyan);

        // 设置相机位置
        customViewerTuiyan.viewer.camera.flyTo({
          destination: Cesium.Rectangle.fromDegrees(30, 0, 180, 50),
          duration: 0
        });

        // 发出事件
        emit("update:customViewerTuiyan", customViewerTuiyan);
        emit("viewer-ready", customViewerTuiyan);

        isInitialized.value = true;
        initRetryCount.value = 0;
      } catch (error) {
        console.error('初始化地图失败:', error);
        destroyViewer();

        // 重试机制
        if (initRetryCount.value < MAX_RETRY_COUNT) {
          initRetryCount.value++;
          setTimeout(() => {
            initMap();
          }, 1000);
        } else {
          console.error('达到最大重试次数，初始化失败');
        }
      } finally {
        isInitializing.value = false;
      }
    };

    // 首次挂载
    onMounted(async () => {
      await nextTick();
      await initMap();
    });

    // 从缓存激活
    onActivated(async () => {
      // 强制重新初始化
      destroyViewer();
      await nextTick();
      await initMap();
    });

    // 组件失活
    onDeactivated(() => {
      simulStore.reAllStepsList()
      destroyViewer();

    });

    // 组件销毁
    onBeforeRouteLeave(() => {
      destroyViewer();
    });

    onBeforeUnmount(() => {
      destroyViewer();
    });

    return {
      destroyViewer
    };
  },
});
</script>

<style scoped>
.cesium-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
</style>
